from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django.conf import settings


class Category(models.Model):
    """博客分类模型"""
    name = models.CharField(_("分类名称"), max_length=100)
    slug = models.SlugField(_("URL别名"), unique=True)
    description = models.TextField(_("分类描述"), blank=True)

    class Meta:
        verbose_name = _("分类")
        verbose_name_plural = _("分类")
        ordering = ['name']

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('category_detail', kwargs={'slug': self.slug})


class Tag(models.Model):
    """博客标签模型"""
    name = models.CharField(_("标签名称"), max_length=50)
    slug = models.SlugField(_("URL别名"), unique=True)

    class Meta:
        verbose_name = _("标签")
        verbose_name_plural = _("标签")
        ordering = ['name']

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('tag_detail', kwargs={'slug': self.slug})


class Post(models.Model):
    """博客文章模型"""
    STATUS_CHOICES = (
        ('draft', _('草稿')),
        ('published', _('已发布')),
        ('scheduled', _('定时发布')),
    )

    title = models.CharField(_("标题"), max_length=200)
    slug = models.SlugField(_("URL别名"), max_length=200, unique_for_date='publish_date')
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='blog_posts',
        verbose_name=_("作者")
    )
    content = models.TextField(_("内容"))
    summary = models.TextField(_("摘要"), blank=True)
    category = models.ForeignKey(
        Category,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='posts',
        verbose_name=_("分类")
    )
    tags = models.ManyToManyField(
        Tag,
        blank=True,
        related_name='posts',
        verbose_name=_("标签")
    )
    featured_image = models.ImageField(
        _("特色图片"),
        upload_to='blog/featured_images/%Y/%m/',
        blank=True,
        null=True
    )
    status = models.CharField(
        _("状态"),
        max_length=10,
        choices=STATUS_CHOICES,
        default='draft'
    )
    publish_date = models.DateTimeField(_("发布时间"), default=timezone.now)
    created_at = models.DateTimeField(_("创建时间"), auto_now_add=True)
    updated_at = models.DateTimeField(_("更新时间"), auto_now=True)
    views = models.PositiveIntegerField(_("浏览量"), default=0)

    class Meta:
        verbose_name = _("文章")
        verbose_name_plural = _("文章")
        ordering = ['-publish_date']
        indexes = [
            models.Index(fields=['-publish_date']),
        ]

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        # 确保 slug 不为空
        if not self.slug:
            from django.utils.text import slugify
            self.slug = slugify(self.title)
            if not self.slug:
                self.slug = f'post-{self.id}'
            self.save(update_fields=['slug'])

        return reverse('post_detail', kwargs={
            'year': self.publish_date.year,
            'month': self.publish_date.month,
            'day': self.publish_date.day,
            'slug': self.slug
        })

    def save(self, *args, **kwargs):
        if not self.slug:
            from django.utils.text import slugify
            self.slug = slugify(self.title)

            # 确保 slug 是唯一的
            original_slug = self.slug
            count = 1
            while Post.objects.filter(slug=self.slug, publish_date__year=self.publish_date.year,
                                      publish_date__month=self.publish_date.month,
                                      publish_date__day=self.publish_date.day).exists():
                self.slug = f"{original_slug}-{count}"
                count += 1

        super().save(*args, **kwargs)


class Comment(models.Model):
    """博客评论模型"""
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name=_("文章")
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name=_("作者")
    )
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='replies',
        verbose_name=_("父评论")
    )
    content = models.TextField(_("内容"))
    created_at = models.DateTimeField(_("创建时间"), auto_now_add=True)
    updated_at = models.DateTimeField(_("更新时间"), auto_now=True)
    active = models.BooleanField(_("是否显示"), default=True)

    class Meta:
        verbose_name = _("评论")
        verbose_name_plural = _("评论")
        ordering = ['created_at']

    def __str__(self):
        return f'评论 by {self.author.username} on {self.post}'

